﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
namespace PaperCut.Classes
{
    public class GeometryHelper
    {
        public static Point? LinesIntersect(Point p1, Point p2, Point p3, Point p4)
        {


            double A1 = p2.Y - p1.Y;
            double B1 = p1.X - p2.X;
            double C1 = p1.X * p2.Y - p2.X * p1.Y;

            double A2 = p4.Y - p3.Y;
            double B2 = p3.X - p4.X;
            double C2 = p3.X * p4.Y - p4.X * p3.Y;

            double delta = A1 * B2 - A2 * B1;
            if (delta == 0) return null;
      
            double x = (B2 * C1 - B1 * C2) / delta;
            double y = (A1 * C2 - A2 * C1) / delta;

            if (
                (Math.Min(p1.X, p2.X) <= x) && (x <= Math.Max(p1.X, p2.X)) &&
                (Math.Min(p1.Y, p2.Y) <= y) && (y <= Math.Max(p1.Y, p2.Y)) &&
                (Math.Min(p3.X, p4.X) <= x) && (x <= Math.Max(p3.X, p4.X)) &&
                (Math.Min(p3.Y, p4.Y) <= y) && (y <= Math.Max(p3.Y, p4.Y))
                )
            {
                return new Point(x, y);
            }
            else
            {
                return null;
            }

        }

        public static Point  GetLinePointAt(double t, Point start, Point end)
        {
            /* Formula from Wikipedia article on Bezier curves. */
            double X = (start.X + end.X) * t;
            double Y = (start.Y + end.Y) * t;
            return new Point(X, Y);
        }

        public static double  GetLineLength(Point A, Point B)
        {
            double x_diff = A.X - B.X;
            double y_diff = A.Y - B.Y;
            return Math.Sqrt(x_diff * x_diff + y_diff * y_diff);

        }
        public static double GetPolyArea(List<Point> pts)
        {
            double area = 0;
            int len = pts.Count;
            for (var i = 0; i < len; ++i)
            {
                Point p1 = pts[i], p2 = pts[(i + len - 1) % len];
                area += (p2.X + p1.X) * (p2.Y - p1.Y);
            }
            return Math.Abs(area / 2);
        }
        public static Point LineMiddle(Point p1, Point p2)
        {
            return new Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
        }
        public static double Distance(Point p1, Point p2)
        {
            return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
        }
    }
}
